import { computed } from 'vue';
import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
import { useAppStore } from '@/pinia/app';
import type { DramaEpisode } from '@/api/drama';
import type { UnlockEpisodeUrlInfoMap } from '@/api/pay';

export type PageParam = {
  /** 推广链接ID */
  referralLinkId?: number | string;
  /** 剧集 id */
  episodeId?: number | string;
  /** 短剧 id */
  dramaId?: number | string;
  /** 快手小程序专用的短剧id */
  ksPlayletId?: string;
  /** 快手小程序专用的第几集 */
  ksSeq?: number;
  /** 快手小程序专用的剧集id */
  ksEpisodeId?: string;
  /** 头条短剧 ID */
  tt_album_id?: string;
  /** 头条剧集 ID */
  tt_episode_id?: string;
};

export type ShowEvent = {
  /** 短剧标题 */
  dramaTitle: string;
  /** 支付成功的回调 */
  paySuccess?: (urls: UnlockEpisodeUrlInfoMap) => void;
};

/**
 * 支付解锁后处理解锁的 url
 */
export function trimUnlockList(dramaEpisodeList: DramaEpisode[], urlObj: UnlockEpisodeUrlInfoMap) {
  dramaEpisodeList.forEach((item: DramaEpisode, _index: number) => {
    const curr = urlObj[item.episodeId!];
    if (curr) {
      item.state = 'unlock';
      item.episodeUrl = curr.episodeUrl || item.episodeUrl;
      item.episodeCover = curr.episodeCover || item.episodeCover;
    }
  });

  return dramaEpisodeList;
}

/** 注册基础数据 */
export function useBaseInfo() {
  const appStore = useAppStore();
  const sys = mxpGetSysInfoStore().getSysInfo();
  const loginState = computed(() => appStore.loginState);
  /** 弹出框高度 */
  const popupHeight = computed(() => sys.value.windowHeight * 0.8);
  /** 底部标题栏的 Bottom 偏移 */
  const titleBarBottom = computed(() => {
    const bottom = sys.value.safeAreaInsets?.bottom || 0;
    return Math.floor(bottom || 15);
  });
  /** 是否自动解锁 */
  const isAutoPay = computed(() => appStore.userInfo?.isAutoPay === 1);
  /** 底部安全距离 */
  const safeAreaInsetsBottom = computed(() => sys.value.safeAreaInsets?.bottom || 0);
  const uniPlatform = computed(() => sys.value.uniPlatform);

  /** 视频最小高度 */
  const minVideoHeight = computed(() => Math.min(Math.ceil((sys.value.windowWidth / 9) * 16), sys.value.screenHeight));
  /** swiper高度 */
  const swiperHeight = computed(() => {
    const swH = sys.value.screenHeight - titleBarBottom.value - 40;
    if (swH - 15 >= minVideoHeight.value) {
      return swH - 15;
    } else if (swH >= minVideoHeight.value) {
      return swH;
    } else {
      return minVideoHeight.value;
    }
  });
  /** 是否静音 */
  const muted = computed(getMuted);
  /** 得到是否静音播放 */
  function getMuted() {
    let _muted = false;
    // #ifdef WEB || APP
    _muted = !appStore.lnteraction;
    // #endif
    return _muted;
  }

  return {
    sys,
    /** 是否自动解锁 */
    isAutoPay,
    /** 平台 */
    uniPlatform,
    /** 底部安全距离 */
    safeAreaInsetsBottom,
    /** appStore */
    appStore,
    /** 登录状态 */
    loginState,
    /** 底部标题栏的 Bottom 偏移 */
    popupHeight,
    /** 底部标题栏的 Bottom 偏移 */
    titleBarBottom,
    /** 视频最小高度 */
    minVideoHeight,
    /** swiper高度 */
    swiperHeight,
    /** 静音播放 */
    muted,
  };
}
